package com.oha.laporrayelchurro.service;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.oha.laporrayelchurro.model.BaseModel;

public class ModelService {

	protected DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	
	/**
	 * Guarda o actualiza una entidad
	 * @param model
	 */
	public void saveOrUpdate(BaseModel model){
		datastore.put(model.getEntity());
	}
	
	/**
	 * Obtiene todos los registros
	 * @param entityName
	 * @return
	 */
	protected List<Entity> getAllEntity(String entityName){
		List<Entity> modelList = new ArrayList<Entity>();
		Query q = new Query(entityName);
		PreparedQuery pq = datastore.prepare(q);
		for (Entity entity : pq.asIterable()) {
			modelList.add(entity);
		}
		return modelList;
	}
	
	/**
	 * Obtiene todos los registros
	 * @param entityName
	 * @return
	 */
	protected List<Entity> getAllEntity(String entityName, List<String> sortLst, List<SortDirection> sdList){
		List<Entity> modelList = new ArrayList<Entity>();
		Query q = new Query(entityName);
		for(int i=0; i<sortLst.size(); i++){
			if(sdList!=null && sdList.size()>i){
				q.addSort(sortLst.get(i), sdList.get(i));
			}else{
				q.addSort(sortLst.get(i));
			}
		}
		PreparedQuery pq = datastore.prepare(q);
		for (Entity entity : pq.asIterable()) {
			modelList.add(entity);
		}
		return modelList;
	}
	
}
